package com.algorithm;

/**
 * 加油站
 */
public class GasStation {

    public static int canCompleteCircuit(int[] gas, int[] cost) {
        int totalCost = 0;
        int totalGas = 0;
        for (int i = 0; i < gas.length; i++) {
            totalGas = gas[i] + totalGas;
            totalCost = cost[i] + totalCost;
        }

        if (totalCost > totalGas) {
            return -1;
        }
        int currentGas = 0;
        int start = 0;
        for (int i = 0; i < gas.length; i++) {
            currentGas = currentGas + gas[i] - cost[i];
            if (currentGas < 0) {
                currentGas = 0;
                start = i + 1;
            }
        }
        return start;
    }

    public static void main(String[] args) {
        int[] gas = {1, 2, 3, 4, 5};
        int[] cost = {3, 4, 5, 1, 2};
        int result = canCompleteCircuit(gas, cost);
        System.out.println(result);
    }
}
